package com.hmall.order.interceptors;

import com.hmall.order.utils.ThreadLocal4UserId;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: cuiliangbo
 * @Date: 2022/6/16 11:38
 */
@SuppressWarnings("all")
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String authorization = request.getHeader("authorization");
        //判断用户Id
        if (StringUtils.isEmpty(authorization)){
            //无用户Id，请求禁止
            response.setStatus(403);
            return  false;
        }
            //  有用户Id，则转换为Long
        Long userId = Long.valueOf(authorization);
        //存入ThreadLocal
        ThreadLocal4UserId.setUserId(userId);
        //放行
        return true;
    }

    //业务完成，将ThreadLocal中用户Id删除
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocal4UserId.removeUser();
    }
}
